package cpt202.project.service.impl;

import cpt202.project.dao.BookMapper;
import cpt202.project.dao.RecordMapper;
import cpt202.project.entity.Book;
import cpt202.project.entity.Record;
import cpt202.project.service.BookService;
import cpt202.project.service.exception.DeleteException;
import cpt202.project.service.exception.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookServiceimpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private RecordMapper recordMapper;

    /**
     *
     * @param email 用户的邮箱
     * @param bookname 用户的新帐本的名字
     * @return  若插入成功则返回新帐本在数据库中的id, 若失败将抛出InsertException异常
     */
    @Override
    public Integer add(String email, String bookname) {
        Book book = new Book(email,bookname);
        bookMapper.addBook(book);
        Integer bookid = book.getId();
        if (bookid<=0){
            throw new InsertException("插入出现未知异常");
        }
        else
            return bookid;
    }


    @Override
    public boolean delete(Integer id){
        bookMapper.deleteBook(id);
        Integer result = bookMapper.isExist(id);
        if (result==null)
            return true;
       else
            throw new DeleteException("删除时出现未知异常");
    }


    @Override
    //用户发起切换账本的请求时，返回在该账本中的所有record
    public Record[] switchBook(Integer bookId) {
        return recordMapper.userRecord(bookId);
    }

}
